<template>
  <div>
    <div>
      <!--    搜索框-->
      <div class="mt-4">
        <el-input
            v-model="input"
            placeholder="在此输入想查询的信息"
            class="input-with-select"
            @input="filterSearch"
        >
          <template #prepend>
            <el-select v-model="select" placeholder="选择" style="width: 115px">
              <el-option label="姓名" value="1" />
              <el-option label="联系方式" value="2" />
              <el-option label="编号" value="3" />
            </el-select>
          </template>
          <template #append>
            <el-button :icon="Search" />
          </template>
        </el-input>
      </div>
    </div>
    <!--    表格-->
    <el-table
        ref="tableRef"
        row-key="cid"
        :data="tableData"
        style="width: 100%"
        @sort-change="handleSortChange"
        empty-text="暂无数据"
        @selection-change="handleSelectionChange"
    >
      <!--      编号列-->
      <el-table-column prop="cid" label="编号" width="100" sortable></el-table-column>
      <!--      生日列-->
      <el-table-column
          prop="birthday"
          label="入会时间"
          sortable
          width="200"
          column-key="birthday"
          :formatter="formatTime"
      />
      <!--      姓名列-->
      <el-table-column prop="nickname" label="昵称" width="200" />
      <!--      联系方式列-->
      <el-table-column prop="phone" label="联系方式" width="200" />
      <!--      性别列-->
      <el-table-column
          prop="gender"
          label="性别"
          width="100"
      >
      </el-table-column>
      <!--      积分列-->
      <el-table-column prop="point" label="积分" width="200" />
      <!--      删除编辑列-->
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
              size="small"
              @click="handleEdit(scope.row)"
          >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!--    分页功能-->
    <div class="demo-pagination-block">
      <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          background
          layout="total, prev, pager, next"
          :total="total"
          @current-change="handleCurrentChange"
      />
    </div>
    <!--表单数据-->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle">
      <el-form :model="tableform">
        <!--        生日-->
        <el-form-item label="生日">
          <el-date-picker
              v-model="tableform.birthday"
              type="datetime"
              placeholder="选择日期"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
        <!--        昵称-->
        <el-form-item label="昵称">
          <el-input v-model="tableform.nickname" />
        </el-form-item>
        <!--          联系方式-->
        <el-form-item label="联系方式">
          <el-input v-model="tableform.phone" />
        </el-form-item>
        <!--        性别-->
        <el-form-item label="性别">
          <el-radio-group v-model="tableform.gender">
            <el-radio label="男" />
            <el-radio label="女" />
          </el-radio-group>
        </el-form-item>
        <!--          会员积分-->
        <el-form-item label="会员积分">
          <el-input v-model="tableform.point" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue'
import { Search } from '@element-plus/icons-vue'
import type { TableColumnCtx, TableInstance } from 'element-plus'
import { reactive,computed } from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import axios from "axios";

interface User {
  cid: number
  birthday: string
  name: string
  phone: string
  gender: string
  point: number
}

//表格数据
const tableData = ref([])
let currentPage = ref(1); //定义当前页码初始值为1
const pageSize = ref(12); //定义每页显示的数据条数为5
let total = ref(0); //初始化数据总条数

// 格式化时间
const formatTime = (row) => {
  const date = new Date(row.birthday);
  const year = date.getFullYear();
  const month = ("0" + (date.getMonth() + 1)).slice(-2);
  const day = ("0" + date.getDate()).slice(-2);
  const hour = ("0" + date.getHours()).slice(-2);
  const minute = ("0" + date.getMinutes()).slice(-2);
  const seconds = ("0" + date.getSeconds()).slice(-2)
  return `${year}-${month}-${day} ${hour}:${minute}:${seconds}`;
}

// 使用axios.get()方法获取用户列表
// 在组件挂载后执行回调函数
onMounted(() => {
  getData()
})

// 获取当前页数据
const getData = () => {
  axios.get("http://192.168.166.182:8080/customer/getAll",{
    params: {
      pageNo: currentPage.value,
      pageSize: pageSize.value
    }
  }).then(response => {
    console.log(response.data)
    tableData.value  = response.data.records;
    total.value = response.data.total;
  }).catch(error => {
    console.error(error);
  })
}

//页数改变
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  getData();
}

//排序
const handleSortChange = (sortData) => {
  //解构sortData参数，得到prop和order两个属性
  const { prop,order } = sortData;
  //使用sort方法对当前页面数据进行排序，并更新其值
  tableData.value = tableData.value.sort((a,b) => {
    if(order === 'ascending') { //升序
      return a[prop] === b[prop] ? a.cid - b.cid : a[prop] > b[prop] ? 1 : -1;
    } else { //降序
      return a[prop] === b[prop] ? a.cid - b.cid : a[prop] < b[prop] ? 1 : -1;
    }
  });
}

const input = ref('') //初始化搜索输入框
const select = ref('') //初始化搜索选择栏
//搜索框搜查
const filterSearch = (val) =>{
  //根据姓名搜索
  if(select.value === "1") {
    //搜索框有输入
    if(val.length > 0) {
      axios.get(`http://192.168.166.182:8080/customer/selectByName`,{
        params: {
          name: val,
          pageNo: currentPage.value,
          pageSize: pageSize.value
        }
      }).then(response => {
        console.log(response.data)
        tableData.value = response.data.records;
        total.value = response.data.total;
      }).catch(error => {
        console.error(error)
      })
    } else { //搜索框无输入
      getData() //还原表格数据
    }
  } else if(select.value === "2") { //根据联系方式搜索
    //搜索框有输入
    if(val.length > 0) {
      axios.get(`http://192.168.166.182:8080/customer/selectByPhone`,{
        params: {
          phone: val,
          pageNo: currentPage.value,
          pageSize: pageSize.value
        }
      }).then(response => {
        console.log(response.data)
        tableData.value = response.data.records;
        total.value = response.data.total;
      }).catch(error => {
        console.error(error)
      })
    } else { //搜索框无输入
      getData();
    }
  } else if(select.value === "3") {
    if(val.length > 0) {
      axios.get(`http://192.168.166.182:8080/customer/selectById`,{
        params: {
          id: val,
          pageNo: currentPage.value,
          pageSize: pageSize.value
        }
      }).then(response => {
        console.log(response.data)
        tableData.value = response.data.records;
        total.value = response.data.total;
      }).catch(error => {
        console.error(error)
      })
    } else {
      getData();
    }
  }
}

const dialogFormVisible = ref(false); //初始化弹窗不显示
let tableform = ref({}); //初始化弹窗表单数据
const dialogTitle = ('编辑数据');

//编辑数据按钮事件
const handleEdit = (row) => { //row为当前行的数据
  dialogFormVisible.value = true;
  tableform.value = {...row};
}

//确定修改数据
const onSubmit = () => {
  dialogFormVisible.value = false;
  // 创建一个副本来保存更新后的用户信息
  const updateMember = {...tableform.value}
  console.log(updateMember)
  // 发送 HTTP PUT 请求来更新用户信息
  axios.post(`http://192.168.166.182:8080/customer/changeById`,updateMember)
      .then(reponse => {
        // 处理成功响应
        ElMessage({type:'success',message:'修改成功！'})
        // 重新获取数据，更新表格显示
        getData()
      }).catch(error => {
    // 处理错误
    console.error('更新失败！')
    console.error(error)
  })
}
</script>

<style>
.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
.demo-pagination-block {
  margin-top: 10px;
}
.mt-4 {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}
.bt1 {
  margin-left: 15px;
}
</style>
